﻿using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace Meligo.ModuleExtractor.ExtractorWP
{
    public partial class ExtractorWPUserControl : UserControl
    {
          // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]

        protected string GetClassForWizardStep(object wizardStep)
        {
            WizardStep step = wizardStep as WizardStep;

            if (step == null)
            {
                return "";
            }
            int stepIndex = wzrdSteps.WizardSteps.IndexOf(step);

            if (stepIndex < wzrdSteps.ActiveStepIndex)
            {
                return "prevStep";
            }
            else if (stepIndex > wzrdSteps.ActiveStepIndex)
            {
                return "nextStep";
            }
            else
            {
                return "currentStep";
            }
        }

        protected void wzrdSteps_PreRender(object sender, EventArgs e) 
        {
            Repeater SideBarList = wzrdSteps.FindControl("HeaderContainer").FindControl("SideBarList") as Repeater;
            SideBarList.DataSource = wzrdSteps.WizardSteps; 
            SideBarList.DataBind();
        }



        /// <summary>
        /// BtnExtract_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void BtnExtract_Click(object sender, EventArgs e)
        {
            StringBuilder results = new StringBuilder();

            if (!string.IsNullOrEmpty(this.ddlDocumentLibraries.SelectedValue))
            {
                SPList list = SPContext.Current.Web.Lists[new Guid(this.ddlDocumentLibraries.SelectedValue)];
                SPList targetList = this.GetListIfExists("Elements", SPListTemplateType.DocumentLibrary);

                if (list != null)
                {
                    if (this.ddlPages.SelectedIndex != 0)
                    {
                        results.Append("A page is selected, trying to find it <br />");
                        SPQuery qry = new SPQuery();
                        qry.Query = @"<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + this.ddlPages.SelectedItem.Value + "</Value></Eq></Where>";
                        SPListItemCollection listItems = list.GetItems(qry);
                        if ((listItems != null) && (listItems.Count > 0))
                        {
                            results.Append("Page is found, retrieving the module elements <br />");
                            this.GetModuleAndSave(listItems, list, targetList, this.rbtnaspx.Checked);
                            results.Append("Page is found, DONE retrieving the module elements <br />");
                        }
                    }
                    else
                    {
                        this.GetModuleAndSave(list.Items, list, targetList, this.rbtnaspx.Checked);
                    }
                }
            }
            results.Append("it's working");
            this.litLogger.Text = results.ToString();
        }

        /// <summary>
        /// OnInit
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            wzrdSteps.PreRender+=new EventHandler(wzrdSteps_PreRender);

            this.btnExtract.Click += new EventHandler(this.BtnExtract_Click);
            if (!Page.IsPostBack)
            {
                this.ddlDocumentLibraries.Items.Clear();
                this.ddlDocumentLibraries.Items.Add(string.Empty);

                foreach (SPList lijst in SPContext.Current.Web.Lists)
                {
                    if (lijst is SPDocumentLibrary)
                    {
                        this.ddlDocumentLibraries.Items.Add(new ListItem(lijst.Title, lijst.ID.ToString()));
                    }
                }
            }
        }

        protected void rbtnViewTag_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnViewTag.Checked)
            {
                this.lblScope.Visible = true;
                this.ddlScope.Visible = true;
            }
            else if (!this.rbtnViewTag.Checked)
            {
                this.lblScope.Visible = false;
                this.ddlScope.Visible = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DdlDocumentLibraries_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlPages.Items.Clear();
            if ((this.ddlDocumentLibraries.SelectedItem != null) && (!string.IsNullOrEmpty(this.ddlDocumentLibraries.SelectedItem.Value)))
            {
                SPList list = SPContext.Current.Web.Lists[new Guid(this.ddlDocumentLibraries.SelectedItem.Value)];
                if (list != null)
                {
                    this.ddlPages.Items.Add(string.Empty);
                    foreach (SPListItem item in list.Items)
                    {
                        if (item.File.Name.ToLower().EndsWith("aspx"))
                        {
                            this.ddlPages.Items.Add(new ListItem(item.File.Name, item.ID.ToString()));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// GetListIfExists
        /// </summary>
        /// <param name="listName"></param>
        /// <param name="listType"></param>
        /// <returns></returns>
        private SPList GetListIfExists(string listName, SPListTemplateType listType)
        {
            try
            {
                SPList library = SPContext.Current.Web.Lists.TryGetList(listName);
                if (library == null)
                {
                    Guid listID = SPContext.Current.Web.Lists.Add(listName, string.Empty, listType);
                    return SPContext.Current.Web.Lists[listID];
                }
                else
                {
                    return library;
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// GetModuleAndSave
        /// </summary>
        /// <param name="itemsCollection"></param>
        /// <param name="sourceList"></param>
        /// <param name="targetList"></param>
        /// <param name="aspxExtension"></param>
        private void GetModuleAndSave(SPListItemCollection itemsCollection, SPList sourceList, SPList targetList, bool aspxExtension)
        {
            foreach (SPListItem item in itemsCollection)
            {
                if (item.File.Name.ToLower().EndsWith("aspx"))
                {
                    GenerateModuleFactory.ModuleFactory factory = new GenerateModuleFactory.ModuleFactory();
                    string result = factory.GenerateElementsFile(item.File, sourceList, this.rbtnMakeListviewRelative.Checked, this.rbtnViewTag.Checked, this.rbntExportDefault.Checked, this.txtModulePath.Text, this.txtModuleUrl.Text, this.ddlScope.SelectedItem, this.txtFilePath.Text);
                    string filename = item.Name.Replace(" ", "_");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (TextWriter tw = new StreamWriter(ms))
                        {
                            tw.Write(result);
                            tw.Flush();
                            if (aspxExtension)
                            {
                                targetList.RootFolder.Files.Add(filename, ms.ToArray(), true);
                            }
                            else
                            {
                                filename = filename.ToLower().Replace("aspx", "xml");
                                targetList.RootFolder.Files.Add(filename, ms.ToArray(), true);
                            }
                        }
                    }
                }
            }
        }

    }
}
